<template>
  <div>
    <el-card>
      <el-alert title="添加商品信息" center="" type="info" show-icon>
      </el-alert>
      <el-steps
        :space="200"
        :active="Number(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addform"
        :rules="rules"
        ref="addFormRef"
        label-position="top"
        label-width="100px"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTableLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addform.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addform.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addform.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addform.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addform.goods_cat"
                :options="cateList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id',
                  children: 'children',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTableData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="val"
                  v-for="(val, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handlePreRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 Two-way Data-Binding -->
            <quill-editor
              ref="myQuillEditor"
              v-model="addform.goods_introduce"
            />
            <!--            添加按钮-->
            <el-button type="primary" class="AddBtn" @click="addGoodsBtn"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%"
    >
      <img :src="previewPic" alt="图片预览" class="perviewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import { UserInfoRules } from '@/common/mixin'
import {
  getGoodsListApi,
  getCateAttryIdApi,
  addGoodsListApi
} from '@/Utils/Api/gitGoodsInfoApi'
export default {
  mixins: [UserInfoRules],
  name: 'addGoods',
  data () {
    return {
      activeIndex: '0',
      addform: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      cateList: [],
      // 动态参数列表数据
      manyTableData: [],
      // 静态参数列表数据
      onlyTableData: [],
      // 图片上传地址
      uploadURL: 'https://lianghj.top:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.localStorage.getItem('token')
      },
      previewPic: '',
      previewDialogVisible: false
    }
  },
  components: {},
  created () {
    this.getGoodsList()
  },
  mounted () {},
  methods: {
    // 获得商品分类
    async getGoodsList () {
      const { data } = await getGoodsListApi()
      if (data.meta.status !== 200) {
        this.$message({
          type: 'error',
          message: data.meta.msg
        })
      }
      this.cateList = data.data
      console.log(this.cateList)
    },
    handleChange () {
      console.log(this.addform.goods_cat)
      if (this.addform.goods_cat.length !== 3) {
        this.addform.goods_cat = []
      }
    },
    // 阻止标签页改变
    beforeTableLeave (activeName, oldActiveName) {
      if (
        (this.addform.goods_cat.length !== 3 && oldActiveName === '0') ||
        this.addform.goods_name === ''
      ) {
        this.$message({
          type: 'error',
          message: '请先选择商品分类或者填写商品名称'
        })
        return false
      }
    },
    // 点击tab
    async tabClick () {
      console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        const { data } = await getCateAttryIdApi(this.cateId, { sel: 'many' })
        if (data.meta.status !== 200) {
          return this.$message({
            type: 'error',
            message: '获取动态列表失败'
          })
        }
        console.log(data)
        data.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTableData = data.data
        console.log('动态参数')
      } else if (this.activeIndex === '2') {
        const { data } = await getCateAttryIdApi(this.cateId, { sel: 'only' })

        if (data.meta.status !== 200) {
          return this.$message({
            type: 'error',
            message: '获取静态列表失败'
          })
        }
        this.onlyTableData = data.data
        console.log(data)
        console.log('静态参数')
      }
    },
    // 图片事件
    handlePreview (res) {
      console.log(res)
      this.previewPic = res.response.data.url
      this.previewDialogVisible = true
      console.log('预览图片', res.response.data.url)
    },
    handlePreRemove (res) {
      console.log(res)
      const filePath = res.response.data.tmp_path
      const index = this.addform.pics.findIndex(
        (item) => item.pic === filePath
      )
      this.addform.pics.splice(index, 1)
      console.log(this.addform.pics)
    },
    handleSuccess (res) {
      console.log(res)
      const picInfo = { pic: res.data.tmp_path }
      this.addform.pics.push(picInfo)
      console.log(this.addform.pics)
    },
    // 点击添加
    async  addGoodsBtn () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          this.$message({
            type: 'error',
            message: '请填写必要的表单内容'
          })
          return false
        }
        const form = _.cloneDeep(this.addform)
        console.log(form)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals }
          this.addform.attrs.push(newInfo)
        })
        // 处理静态参数
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals }
          this.addform.attrs.push(newInfo)
        })
        form.attrs = this.addform.attrs
        console.log(form)
        const { data } = await addGoodsListApi(form)
        console.log(data)
        if (data.meta.status !== 201) {
          this.$message({
            type: 'error',
            message: data.meta.msg
          })
        }
        this.$message({
          type: 'success',
          message: data.meta.msg
        })
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cateId () {
      if (this.addform.goods_cat.length === 3) {
        return this.addform.goods_cat[2]
      }
      return null
    }
  },
  watch: {}
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.perviewImg {
  width: 100%;
}
.AddBtn{
    margin-top: 15px;
}
</style>
